/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hadss_avoid_area/component/folder_plugin.dart';

import 'package:hadss_avoid_area/hadss_avoid_area.dart';
import 'package:flutter/services.dart';

void main() {
  const folderStateChannelName = 'avoid_area/folder_state';
  const areaEventChannelName = 'flutter_avoid_area_event';
  const areaMethodChannel = MethodChannel('flutter_avoid_area_method');

  TestWidgetsFlutterBinding.ensureInitialized();

  setUp(() {
    // 模拟 MethodChannel 调用
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger.setMockMethodCallHandler(
      areaMethodChannel,
      (MethodCall methodCall) async {
        if (methodCall.method == 'getWindowAvoidArea') {
          return '{"visible": true, "leftRect": {"left": 0, "top": 0, "width": 0, "height": 0}, "topRect": {"left": 0, "top": 0, "width": 1080, "height": 40}, "rightRect": {"left": 0, "top": 0, "width": 0, "height": 0}, "bottomRect": {"left": 0, "top": 1920, "width": 1080, "height": 40}}';
        } else if (methodCall.method == 'removeAvoidAreaListener') {
          return null;
        }
        return null;
      },
    );
  });

  tearDown(() {
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger.setMockMessageHandler(folderStateChannelName, null);
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger.setMockMessageHandler(areaEventChannelName, null);
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger.setMockMethodCallHandler(areaMethodChannel, null,);
  });

  test('FolderStateStream receives data from EventChannel', () async {
    final folderStateStream = FolderStackPlugin.folderStateEvents;

    final List<dynamic> events = [];

    folderStateStream.listen(events.add);

    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger.handlePlatformMessage(
      folderStateChannelName,
      const StandardMethodCodec().encodeSuccessEnvelope('{"state": 1, "orientation": 0, "bounds": {"left": 0, "right": 100, "top": 0, "bottom": 100}}'),
          (_) {},
    );

    await Future.delayed(const Duration(milliseconds: 10));

    expect(events.isNotEmpty, isTrue);
    for (var event in events) {
      expect(event, isA<FoldingFeature>());
      expect(event.state, FoldStatus.expanded);
    }
  });

  testWidgets('FolderStack widget test', (WidgetTester tester) async {
    await tester.pumpWidget(
      MaterialApp(
        home: FolderStack(
          upperItems: const ['testItem'],
          children: [
            Container(key: const ValueKey('testItem'), child: const Text('Test Widget')),
          ],
        ),
      ),
    );
  
    expect(find.text('Test Widget'), findsOneWidget);
  });

  testWidgets('FoldSplitContainer widget test', (WidgetTester tester) async {
    final foldedLayoutOptions = FoldedRegionLayoutOptions();
    final expandedLayoutOptions = ExpandedRegionLayoutOptions();
    final hoverModeLayoutOptions = HoverModeRegionLayoutOptions();
  
    await tester.pumpWidget(
      MaterialApp(
        home: FoldSplitContainer(
          primary: const Text('Primary Widget'),
          secondary: const Text('Secondary Widget'),
          foldedLayoutOptions: foldedLayoutOptions,
          expandedLayoutOptions: expandedLayoutOptions,
          hoverModeLayoutOptions: hoverModeLayoutOptions,
        ),
      ),
    );
  
    expect(find.text('Primary Widget'), findsOneWidget);
    expect(find.text('Secondary Widget'), findsOneWidget);
  });

  // 测试 getWindowAvoidArea 方法
  test('getWindowAvoidArea test', () async {
    // 假设 AvoidAreaType 存在 system 类型
    final avoidArea = await AvoidAreaApi.getWindowAvoidArea(AvoidAreaType.system);
    expect(avoidArea, isNotNull);
    expect(avoidArea.visible, isTrue);
  });

  // 测试 addAvoidAreaListener 方法
  test('addAvoidAreaListener test', () async {
    bool listenerCalled = false;
    AvoidAreaApi.addAvoidAreaListener((event) {
      listenerCalled = true;
    });
    // 模拟发送事件
    TestDefaultBinaryMessengerBinding.instance?.defaultBinaryMessenger.handlePlatformMessage(areaEventChannelName,
      const StandardMethodCodec().encodeSuccessEnvelope('test event'),
          (_) {},
    );

    await Future.delayed(const Duration(milliseconds: 10));
    expect(listenerCalled, isTrue);
  });
}